import pandas as pd
import numpy as np
'''
cat 对象
'''
df = pd.read_csv('data/learn_pandas.csv',
     usecols = ['Grade', 'Name', 'Gender', 'Height', 'Weight'])
s = df.Grade.astype('category')
print(s.cat)
s.cat.codes.head()

s = s.cat.add_categories('Graduate') # 增加一个毕业生类别
# 对category 增加类别属性
s.cat.categories
# 删除category
s = s.cat.remove_categories('Freshman')
# 设置新类别并把不属于该类别的category进行置空
s = s.cat.set_categories(['Sophomore','PhD']) # 新类别为大二学生和博士
s = s.cat.remove_unused_categories() # 移除了未出现的博士生类别
s = s.cat.rename_categories({'Sophomore':'本科二年级学生'})

'''
序列
'''
s = df.Grade.astype('category')
s = s.cat.reorder_categories(['Freshman', 'Sophomore',
                              'Junior', 'Senior'],ordered=True)
s.cat.as_unordered().head()
'''
排序比较
'''
df.Grade = df.Grade.astype('category')
df.Grade = df.Grade.cat.reorder_categories(['Freshman',
                                            'Sophomore',
                                            'Junior',
                                            'Senior'],ordered=True)
df.sort_values('Grade').head() # 值排序
df.set_index('Grade').sort_index().head() # 索引排序

res1 = df.Grade == 'Sophomore'
res2 = df.Grade == ['PhD']*df.shape[0]
res3 = df.Grade <= 'Sophomore'
res4 = df.Grade <= df.Grade.sample(
                            frac=1).reset_index(
                                      drop=True) # 打乱后比较

'''
区间类别
'''
s = pd.Series([1,2])
# 左开右闭
pd.cut(s, bins=2)
# 左开又开 不指定分割点就是安装平分计算区间
pd.cut(s, bins=2, right=False)
# 指定分割点，安装给的分割点进行分割区间并与给定的区间有交集
pd.cut(s, bins=[-np.infty, 1.2, 1.8, 2.2, np.infty])
s = pd.Series([1,2])
res = pd.cut(s, bins=2, labels=['small', 'big'], retbins=True)# 划分区间并起个名字对应label，不返回分割点

s = df.Weight
pd.qcut(s, q=3).head()

pd.qcut(s, q=[0,0.2,0.8,1]).head()

my_interval = pd.Interval(0, 1, 'right')
'''
判断是否在区间内
'''
0.5 in my_interval
my_interval_2 = pd.Interval(0.5, 1.5, 'left')
'''
两个集合判断交集
'''
my_interval.overlaps(my_interval_2)

# 传入分割点
pd.IntervalIndex.from_breaks([1,3,6,10], closed='both')
pd.IntervalIndex.from_arrays(left = [1,3,6,10],
                             right = [5,4,9,11],
                             closed = 'neither')
pd.IntervalIndex.from_tuples([(1,5),(3,4),(6,9),(10,11)],
                              closed='neither')
pd.interval_range(start=1,end=5,periods=8)
pd.interval_range(end=5,periods=8,freq=0.5)
# 强制改变越来的closed
pd.IntervalIndex([my_interval, my_interval_2], closed='left')

id_interval = pd.IntervalIndex(pd.cut(s, 3))
id_demo = id_interval[:5] # 选出前5个展示
print(id_demo.left)
print(id_demo.right)
print(id_demo.mid)
print(id_demo.length)
# 判断是否包含
id_demo.contains(4)
# 判断是否有交集
id_demo.overlaps(pd.Interval(40,60))



